package com.bw.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.RandomUtil;
import com.bw.entity.User;
import com.bw.mapper.UserMapper;
import org.spring.kun.common.ZzyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    UserMapper userMapper;

    /**
     * 返回一个图片验证码
     * @param response
     * @throws IOException
     */
    @RequestMapping("/picCode.do")
    public void picCode(String uuid, HttpServletResponse response) throws IOException {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100,5,50);

        String code = lineCaptcha.getCode();
        redisTemplate.opsForValue().set(uuid,code,3,TimeUnit.MINUTES);
        lineCaptcha.write(response.getOutputStream());
    }
    @RequestMapping("/loginPage.do")
    public String loginPage(){

        return "login";
    }

    @RequestMapping("/sendCode.do")
    @ResponseBody
    public Boolean sendCode(String phone){

        String code = RandomUtil.randomNumbers(5);
        ZzyUtils.sendSms(phone,code,5);
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        return true;
    }


    @RequestMapping("/login.do")
    public String login(User loginUser, Model model){

        String phoneCode = loginUser.getPhoneCode(); //用户输入的验证码

        Object code = redisTemplate.opsForValue().get(loginUser.getPhone());

        if (!phoneCode.equals(code)){
            model.addAttribute("error","短信验证码错误");
            return "login";
        }
        String uuid = loginUser.getUuid();// 用户的唯一标识
        String picCode = loginUser.getPicCode();//用户输入的图片验证码
        Object picCodeRedis = redisTemplate.opsForValue().get(uuid);

        if (!picCode.equals(picCodeRedis)){
            model.addAttribute("error","图片验证码错误");
            return "login";
        }

        model.addAttribute("phone",loginUser.getPhone());
        return "success";
    }
}
